package ccnGame;

/**
 * A Word Chain game program.
 * 
 * written by Gihoon Kim.
 * 
 * 
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JPanel;

import ccnGame.CCNGameNet.CCNGameCallBack;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;


public class WordChain extends JFrame implements ActionListener, CCNGameCallBack{
	private static final long serialVersionUID = -8779269133035264361L;
	
	char _last;
	
	//game window
	protected JTextArea  _messageArea= new JTextArea(10, 32);
	private JTextField  _textField= new JTextField(32);
	private JButton startbutton = new JButton();
	private int count = 0;
	private final CCNGameNet _game;
	private String _current;
	private String nickname;
	private Iterator<String> _userlist;
	
	public WordChain(String namespace, String nick) throws MalformedContentNameStringException {
		
		nickname = nick;
		_game = new CCNGameNet(this, namespace, nickname);
		
		if((null!=nickname)&&(nickname.length()>0)){
			addWindowListener(
			           new WindowAdapter() {
			               public void windowClosing(WindowEvent e) {
			                   try {
								stop();
							} catch (IOException e1) {
								System.out.println("IOException shutting down listener: " + e1);
								e1.printStackTrace();
							}
			               }
			           }
		    );
			
			//make window
			_messageArea.setEditable(false);
			_messageArea.setBackground(Color.LIGHT_GRAY);
			_messageArea.setLineWrap(true);
			_textField.addActionListener(this);
			
			Container content = getContentPane();
			
			/*
			JPanel pane = new JPanel();
			pane.add(new JScrollPane(_messageArea), BorderLayout.CENTER);
			pane.add(_textField, BorderLayout.SOUTH);
			content.add(pane);
			*/
			content.add(new JScrollPane(_messageArea), BorderLayout.CENTER);
			content.add(_textField, BorderLayout.SOUTH);
			
			//display the window
			setTitle("Wordchain: ["+namespace+"]");
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			pack();
			_textField.requestFocusInWindow();
			setContentPane(content);
		
		}
		else{
			JOptionPane.showMessageDialog(this, "Log in Error", "WARNING", JOptionPane.WARNING_MESSAGE);
		}
	}
	
	/**
	 * Process input to textfield.
	 */
	public void actionPerformed(ActionEvent e) {
		try{
			String newText = _textField.getText();
			if((null != newText) && (newText.length() >0)){
				
				if(_current.compareTo(nickname) ==0){
					if(perform_wordchain(newText)!=-1)
						_game.sendMessage(newText);
				}
				else{
					recvMessage("Not you're turn\n");
				}
			}
		}
		catch(Exception e1){
			System.err.println("Exception input : "+e1.getClass().getName()+": "+e1.getMessage());
			e1.printStackTrace();
			recvMessage("Exception input : " + e1.getClass().getName()+": "+e1.getMessage());
		}
		_textField.setText("");
		_textField.requestFocusInWindow();
	}
	
	public int perform_wordchain(String msg){
		int result=1;
		if(count==0){
			_last = msg.charAt(msg.length()-1);
		}else{
			if(compareProcess(msg)==-1){
				recvMessage("A first letter should be same as a last letter of a last word.\n");
				result = -1;
			}
		}
		return result;
	}

	/**
	 * Add a message to the output
	 * @param message
	 */
	public void recvMessage(String message){
		_messageArea.insert(message, _messageArea.getText().length());
		_messageArea.setCaretPosition(_messageArea.getText().length());
	}
	
	public void recvMessage(Message m1) {
		String sender = m1.getName();
		String msg = m1.getMsg();
		String result;
		
		result = "[" + sender+"] "+msg;
		
		if(m1.getState() == Message.SYSTEM_MESSAGE ){
			recvMessage(result+"\n");
	
			_userlist = _game.getUserList();
			_current = _userlist.next();
			recvMessage("== "+_current+" turn! \n");
		}
		else if(m1.getState() == Message.SHUTDOWN_MESSAGE || m1.getState() == Message.LOGIN_MESSAGE){
			recvMessage(result+"\n");
			recvMessage("== START NEW GAME ==\n");
			_userlist = _game.getUserList();
			_current = _userlist.next();
			recvMessage("== "+_current+" turn! \n");
		}
		else{
			/*if(count==0){
				_last = msg.charAt(msg.length()-1);
				count++;
			}
			if(compareProcess(msg)==-1){
				result = result+" - A first letter should be same as a last letter of a last word.";
			}*/
			_last = msg.charAt(msg.length()-1);
			if(count==0) count++;
			recvMessage(result+"\n");
			if(_userlist.hasNext()){
				_current = _userlist.next();
			}else{
				_userlist = _game.getUserList();
				_current = _userlist.next();
			}
			recvMessage("== "+_current+" turn! \n");
				/*
			try {
				_game.sendMessage(result);
			} catch (ContentEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}
	}

	public int compareProcess(String s){
		if(s.charAt(0) == _last) return 1;
		else return -1;
	}

	
	public static void usage(){
		System.err.println("usage : WordChain <ccn URl>");	
	}
	/*
	public static void main(String[] args){
		if(args.length!=1){
			usage();
			System.exit(-1);
		}
		WordChain client;
		try{
			client = new WordChain(args[0]);
			client.start();
		}catch (MalformedContentNameStringException e) {
			System.err.println("Not a valid ccn URI: " + args[0] + ": " + e.getMessage());
			e.printStackTrace();
		} catch (ConfigurationException e) {
			System.err.println("Configuration exception running WordChain: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("IOException handling WordChain messages: " + e.getMessage());
			e.printStackTrace();
		}
		
		
	}
	*/
	/**
	 * Called by window thread when window is closed.
	 */
	protected void stop() throws IOException{
		_game.shutDown();
	}
	
	/**
	 * This blocks until _game.shutdown() called
	 * @throws IOException 
	 * @throws MalformedContentNameStringException 
	 * @throws ConfigurationException 
	 */
	protected void start() throws ConfigurationException, MalformedContentNameStringException, IOException {
		_game.connect();
	}
	
}
